import { domHasClass } from '@vimi/utils-tool'

/**
 * 把 element-ui 的 el-dialog 变为可拖拽的弹窗
 *
 * @example
 *
 * ```html
 * <el-dialog :visible.sync="visible" v-dialog-drag>
 *    <div>Content</div>
 * </el-dialog>
 *
 * <!-- 不限制边界 -->
 * <el-dialog :visible.sync="visible" v-dialog-drag.loose>
 *    <div>Content</div>
 * </el-dialog>
 * ````
 */
export default {
  inserted(el, binding) {
    const dialogEl = el.querySelector('.el-dialog')
    const headerEl = el.querySelector('.el-dialog__header')
    if (!dialogEl || !headerEl) return

    headerEl.style.cssText += ';cursor:move;'
    el.style['overflow-x'] = 'hidden'

    const { loose = false } = binding.modifiers
    let draging = false
    let hasInit = false
    const point = { l: 0, t: 0, w: 0, h: 0, hw: 0, hh: 0, ft: 0, fb: 0, ot: 0 }

    function handleMouseUp() {
      document.removeEventListener('mouseup', handleMouseUp)
      document.removeEventListener('mousemove', handleMouseMove)
      draging = false
    }

    function handleMouseMove(e) {
      e.preventDefault && e.preventDefault()
      e.stopPropagation && e.stopPropagation()

      if (!draging) return

      let tlL = e.clientX - point.l
      let tlT = e.clientY - point.t

      // 边界处理
      if (!loose) {
        if (tlL < -point.hw) {
          tlL = -point.hw
        } else if (tlL > point.hw) {
          tlL = point.hw
        }
        if (tlT < -point.ft) {
          tlT = -point.ft
        } else if (tlT > point.fb) {
          tlT = point.fb
        }
      }
      if (tlT < -point.ot) {
        tlT = -point.ot
      }

      dialogEl.style.top = `${tlT}px`
      dialogEl.style.left = `${tlL}px`
    }

    function onMouseDown(e) {
      const { target } = e
      if (domHasClass(target, 'el-dialog__close')) {
        return
      }

      if (!draging) {
        document.addEventListener('mouseup', handleMouseUp)
        document.addEventListener('mousemove', handleMouseMove)
      }

      if (!hasInit) {
        point.ot = dialogEl.offsetTop
        hasInit = true
      }

      const top = dialogEl.style.top.replace('px', '')
      const left = dialogEl.style.left.replace('px', '')

      const clientH = document.documentElement.clientHeight || document.body.clientHeight || 900

      draging = true
      point.t = e.clientY - top
      point.l = e.clientX - left
      point.w = dialogEl.offsetWidth
      point.h = dialogEl.offsetHeight
      point.ft = dialogEl.offsetTop - top
      point.fb = clientH - point.ft - point.h
      point.hw = point.w / 2
      point.hh = point.h / 2
    }

    headerEl.addEventListener('mousedown', onMouseDown)
  },
}
